<?php
/*
* PHPwork模块化工作台 - EasyWeChat
* EasyWeChat开发文档：https://www.easywechat.com/docs
*/
use EasyWeChat\Factory;

if( isset( $GLOBALS['config']['微信公众号'] ) ){

    $GLOBALS['wechat']['config'] = [
        'appid'     => $GLOBALS['config']['微信公众号']['appid'],
        'appsecret' => $GLOBALS['config']['微信公众号']['appsecret'],
        'token'     => $GLOBALS['config']['微信公众号']['token'],
        'aes_key'   => $GLOBALS['config']['微信公众号']['aes_key'],
    ];

    $GLOBALS['wechat']['app'] = Factory::officialAccount([
        'app_id'  => $GLOBALS['config']['微信公众号']['appid'],
        'secret'  => $GLOBALS['config']['微信公众号']['appsecret'],
        'token'   => $GLOBALS['config']['微信公众号']['token'],
        'aes_key' => $GLOBALS['config']['微信公众号']['aes_key'],

        'response_type' => 'array',
    ]);

}

if( isset( $GLOBALS['config']['微信支付'] ) ){

    $GLOBALS['wechat']['config']['mch_id'] = $GLOBALS['config']['微信支付']['mch_id'] ;         //商户号
    $GLOBALS['wechat']['config']['apikey'] = $GLOBALS['config']['微信支付']['apikey'] ;         // API 密钥
    $GLOBALS['wechat']['config']['notify_url'] = _APP_URL_ . '/data/pay/wechat/notify.php';     // 支付成功后回调地址

}


// 获得用户信息
if (!function_exists('wechat_oauth_userinfo')) {
    function wechat_oauth_userinfo(){
        // 未登录  这里应该保存到数据库里判断  有可能取消关注了不能简单判断数据库 ['snsapi_userinfo']
        if ( isset($_SESSION['wechat_user']) && $_SESSION['wechat_user']!='' 
                && isset($_SESSION['wechat_user']['original']['openid']) 
                && $_SESSION['wechat_user']['original']['openid']!='' ){

            if( !isset($GLOBALS['wechat']['member']) ){
                //判断是否存在unionid
                if(isset($_SESSION['wechat_user']['original']['unionid']) && $_SESSION['wechat_user']['original']['unionid']!=''){
                    $unionid=$_SESSION['wechat_user']['original']['unionid'];
                    //添加用户到系统用户表
                    $sql="select * from ".tablename('sys_member')." where unionid='".$unionid."' ";
                }else{
                    $unionid=0;
                    //添加用户到系统用户表
                    $sql="select * from ".tablename('sys_member')." where openid='".$_SESSION['wechat_user']['original']['openid']."' ";
                }
                $member=$GLOBALS['db']->query($sql)->fetch(\PDO::FETCH_ASSOC);
                //判断用户是否存在
                if($member){

                    if(strpos( $member['unionid_openid'],$_SESSION['wechat_user']['original']['openid']) !== false){ 
                        //全局变量用户信息
                        $GLOBALS['wechat']['member']= $member;
                    }else{
                        if($member['unionid_openid']==''){
                            $data=['unionid_openid'=>$_SESSION['wechat_user']['original']['openid'].','];
                        }else{
                            $data=['unionid_openid'=> $member['unionid_openid'].$_SESSION['wechat_user']['original']['openid'].','];
                        }
                        if($unionid!=0){
                            //修改系统用户表的所有openid
                            pdo_update('sys_member',$data,['unionid'=>$unionid]);
                        }else{
                            //修改系统用户表的所有openid
                            pdo_update('sys_member',$data,['openid'=> $_SESSION['wechat_user']['original']['openid'] ]);
                        }
                        //全局变量用户信息
                        $GLOBALS['wechat']['member']= $member;
                    }
                    
                }else{
                    //添加用户信息
                    $data=array(
                        'nickname'=> $_SESSION['wechat_user']['nickname'],
                        'avatar'=> $_SESSION['wechat_user']['avatar'],
                        'openid'=> $_SESSION['wechat_user']['original']['openid'],
                        'unionid'=> $unionid,
                        'unionid_openid'=> $_SESSION['wechat_user']['original']['openid'].',',
                        'create_time'=> time(),
                        'status'=>1,
                    );
                    $ok = pdo_insert('sys_member',$data);

                    $GLOBALS['wechat']['member']=$GLOBALS['db']->query($sql)->fetch(\PDO::FETCH_ASSOC);
                }
            }

        }else{

            $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ?"https://": "http://";

            //$protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

            //$_SESSION['target_url'] = url( [ 'demo_wechat' ,'index','oauth','index.php'] );
            $_SESSION['target_url'] = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

            $response = $GLOBALS['wechat']['app']->oauth->scopes(['snsapi_userinfo'])
                            ->redirect( url( [ 'api' ,'wechat','oauth','index.php'] ) );
            $response->send() ;
            exit();
        }


    }
}

//获取小程序用户openid和unionid   ---  手动调用（非自动加载）
if(!function_exists('wxapp_userinfo')){
    function wxapp_userinfo($code){
        $wxUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$GLOBALS['config']['微信小程序']['appid'].'&secret='.$GLOBALS['config']['微信小程序']['appsecret'].'&js_code='.$code.'&grant_type=authorization_code';
        $result = curl_get($wxUrl);//请求拼接好的url
        $wxResult = json_decode($result, true);
        if (empty($wxResult)) {
            $arr['code']=$wxResult;
        } else {
            $loginFail = array_key_exists('errcode', $wxResult);
            if ($loginFail) {//请求失败
                $arr['code']=$loginFail;
            } else {//请求成功
                $arr['code']=200;
                $arr['data'] = $wxResult;
            }
        }
        return $arr;
    }
}

//保存小程序用户信息  ---  手动调用（非自动加载）
if(!function_exists('wxapp_userinfo_save')){
    function wxapp_userinfo_save($openid,$unionid,$nickname,$avatar){
		if($unionid !== 0){
			$sys_user=pdo_fetch(" select * from ".tablename('sys_member')." where unionid='".$unionid."' ");
		}else{
			$sys_user=pdo_fetch(" select * from ".tablename('sys_member')." where openid='".$openid."' ");
		}
        
        if($sys_user){
            if(strpos( $sys_user['unionid_openid'],$openid) !== false){ 
                $arr['code']=200;
                $arr['message']='用户信息获取成功!';
                $arr['data']=$sys_user;
            }else{
                if($sys_user['unionid_openid']==''){
                    $data=['unionid_openid'=>$openid.','];
                }else{
                    $data=['unionid_openid'=>$sys_user['unionid_openid'].$openid.','];
                }
                //修改系统用户表的所有openid
                $ok=pdo_update('sys_member',$data,['unionid'=>$unionid]);
                if($ok){
                    $arr['code']=200;
                    $arr['message']='用户信息获取成功!';
                    $arr['data']=$sys_user;
                }else{
                    $arr['code']=400;
                    $arr['message']='用户信息插入失败,请重试!';
                    $arr['data']=$sys_user;
                }
            }
        }else{
            //添加用户信息
            $data=array(
                'nickname'=> $nickname,
                'avatar'=> $avatar,
                'openid'=> $openid,
                'unionid'=> $unionid,
                'unionid_openid'=> $openid.',',
                'create_time'=> time(),
                'status'=>1,
            );
            $ok = pdo_insert('sys_member',$data);
            if($ok){
                $user_info=pdo_fetch("select * from ".tablename('sys_member')." where uid=".$ok);
                if($user_info){
                    $arr['code']=200;
                    $arr['message']='用户信息获取成功!';
                    $arr['data']=$user_info;
                }else{
                    $arr['code']=400;
                    $arr['message']='用户信息获取失败!';
                    $arr['data']='';
                }
            }else{
                $arr['code']=400;
                $arr['message']='用户信息插入失败,请重试!';
                $arr['data']=$sys_user;
            }
        }
        return $arr;
    }
}

//curl接口---配合wxapp_userinfo函数使用
if(!function_exists('curl_get')){
    function curl_get($url, &$httpCode = 0) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
        //不做证书校验,部署在linux环境下请改为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $file_contents = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $file_contents;
    }
}


